from django.db import models
from django.contrib.auth.models import User
from django.db.models import Max
import re

class Asset(models.Model):
    # 设备状态选择
    STATUS_CHOICES = (
        ('active', '正常'),
        ('maintenance', '维修中'),
        ('retired', '已报废'),
        ('out_of_service', '停用'),
    )
    
    # 设备类型选择
    TYPE_CHOICES = (
        ('computer', '电脑'),
        ('printer', '打印机'),
        ('network', '网络设备'),
        ('server', '服务器'),
        ('other', '其他'),
    )
    
    name = models.CharField(max_length=100, verbose_name='设备名称')
    model = models.CharField(max_length=100, verbose_name='设备型号')
    serial_number = models.CharField(max_length=100, unique=True, verbose_name='序列号')
    code = models.CharField(max_length=20, unique=True, blank=True, verbose_name='设备编码')
    asset_type = models.CharField(max_length=20, choices=TYPE_CHOICES, default='other', verbose_name='设备类型')
    status = models.CharField(max_length=20, choices=STATUS_CHOICES, default='active', verbose_name='设备状态')
    
    # 设备信息
    purchase_date = models.DateField(null=True, blank=True, verbose_name='购买日期')
    warranty_expiry = models.DateField(null=True, blank=True, verbose_name='保修到期')
    purchase_price = models.DecimalField(max_digits=10, decimal_places=2, null=True, blank=True, verbose_name='购买价格')
    
    # 位置信息
    location = models.CharField(max_length=200, blank=True, verbose_name='位置')
    department = models.CharField(max_length=100, blank=True, verbose_name='部门')
    
    # 关联信息
    assigned_to = models.ForeignKey(User, on_delete=models.SET_NULL, null=True, blank=True, 
                                  related_name='assets', verbose_name='分配给')
    
    # 时间信息
    created_at = models.DateTimeField(auto_now_add=True, verbose_name='创建时间')
    updated_at = models.DateTimeField(auto_now=True, verbose_name='更新时间')
    
    # 备注
    notes = models.TextField(blank=True, verbose_name='备注')
    
    class Meta:
        verbose_name = '设备'
        verbose_name_plural = '设备'
        ordering = ['name']

    def __str__(self):
        return f"{self.code} - {self.name} ({self.model})" if self.code else f"{self.name} - {self.model}"

    def save(self, *args, **kwargs):
        if not self.code:
            self.code = self.generate_device_code()
        super().save(*args, **kwargs)

    def generate_device_code(self):
        """自动生成设备编码: DEPT-TYPE-序号"""
        # 获取部门代码（取前3个字母大写）
        dept_code = self.department[:3].upper() if self.department else 'GEN'
        dept_code = re.sub(r'[^A-Z]', '', dept_code) or 'GEN'
        
        # 获取设备类型代码
        type_mapping = {
            'computer': 'COM',
            'printer': 'PRN',
            'network': 'NET',
            'server': 'SVR',
            'other': 'OTH'
        }
        type_code = type_mapping.get(self.asset_type, 'OTH')
        
        # 查找同部门同类型设备的最大序号
        existing_codes = Asset.objects.filter(
            department=self.department,
            asset_type=self.asset_type
        ).exclude(code__isnull=True).exclude(code='')
        
        max_number = 0
        for asset in existing_codes:
            if asset.code and '-' in asset.code:
                try:
                    parts = asset.code.split('-')
                    if len(parts) == 3:
                        number = int(parts[2])
                        max_number = max(max_number, number)
                except (ValueError, IndexError):
                    continue
        
        # 生成新序号
        new_number = max_number + 1
        return f"{dept_code}-{type_code}-{new_number:03d}"

class MaintenanceHistory(models.Model):
    """设备维修历史"""
    asset = models.ForeignKey(Asset, on_delete=models.CASCADE, related_name='maintenance_history', verbose_name='设备')
    description = models.TextField(verbose_name='维修描述')
    cost = models.DecimalField(max_digits=10, decimal_places=2, default=0, verbose_name='维修成本')
    performed_by = models.ForeignKey(User, on_delete=models.SET_NULL, null=True, blank=True, 
                                   related_name='performed_maintenance', verbose_name='维修人员')
    maintenance_date = models.DateField(verbose_name='维修日期')
    next_maintenance_date = models.DateField(null=True, blank=True, verbose_name='下次维修日期')
    created_at = models.DateTimeField(auto_now_add=True, verbose_name='记录时间')
    
    class Meta:
        verbose_name = '维修历史'
        verbose_name_plural = '维修历史'
        ordering = ['-maintenance_date']

    def __str__(self):
        return f"{self.asset.name} - {self.maintenance_date}"
